import { useAdvancedCacheStore } from '@/stores/modules/advancedCache'
import { characterInfo } from '@/api'
import type { RoleInfo } from '@/api/interface'

export interface CacheConfig {
  expireTime?: number
  enableStaleWhileRevalidate?: boolean
  maxRetries?: number
  retryDelay?: number
}

export class CacheService {
  private cacheStore = useAdvancedCacheStore()
  private defaultConfig: Required<CacheConfig> = {
    expireTime: 5 * 60 * 1000, // 5分钟
    enableStaleWhileRevalidate: true, // 启用过期缓存降级
    maxRetries: 3,
    retryDelay: 1000
  }

  // 角色列表缓存策略
  async getRoleList(params: {
    keyword?: string
    category?: string
    pageNum?: number
    pageSize?: number
  }, config?: CacheConfig): Promise<{
    code: number
    data: {
      list: RoleInfo[]
      total: number
      pageNum: number
      pageSize: number
      pages: number
      hasNextPage: boolean
    }
  }> {
    const finalConfig = { ...this.defaultConfig, ...config }
    const cacheKey = this.cacheStore.generateCacheKey('roleList', params)
    
    // 检查缓存
    const cached = this.cacheStore.getCache(cacheKey)
    if (cached) {
      console.log('使用缓存数据:', cacheKey)
      return cached
    }

    // 如果启用过期缓存降级，检查是否有过期缓存
    if (finalConfig.enableStaleWhileRevalidate) {
      const expiredCache = this.cacheStore.caches[cacheKey]
      if (expiredCache) {
        console.log('使用过期缓存作为降级:', cacheKey)
        // 异步更新缓存
        this.updateCacheInBackground(cacheKey, params, finalConfig)
        return expiredCache.data
      }
    }

    // 缓存未命中，获取新数据
    return this.fetchAndCache(cacheKey, params, finalConfig)
  }

  // 获取数据并缓存
  private async fetchAndCache(
    cacheKey: string, 
    params: any, 
    config: Required<CacheConfig>
  ) {
    let retryCount = 0
    
    while (retryCount < config.maxRetries) {
      try {
        console.log('从服务器获取数据:', cacheKey, `重试次数: ${retryCount}`)
        const result = await characterInfo.list(params)
        
        if (result.code === 0 && result.data) {
          // 缓存成功的数据
          this.cacheStore.setCache(cacheKey, result, config.expireTime)
          console.log('数据已缓存:', cacheKey)
          return result
        } else {
          throw new Error(`接口返回异常: ${result.message || '未知错误'}`)
        }
      } catch (error) {
        retryCount++
        console.error(`获取数据失败 (${retryCount}/${config.maxRetries}):`, error)
        
        if (retryCount >= config.maxRetries) {
          // 所有重试都失败，尝试返回过期缓存
          const expiredCache = this.cacheStore.caches[cacheKey]
          if (expiredCache) {
            console.warn('使用过期缓存作为最后降级:', cacheKey)
            return expiredCache.data
          }
          throw error
        }
        
        // 等待后重试
        await new Promise(resolve => setTimeout(resolve, config.retryDelay * retryCount))
      }
    }
  }

  // 后台更新缓存
  private async updateCacheInBackground(
    cacheKey: string, 
    params: any, 
    config: Required<CacheConfig>
  ) {
    try {
      const result = await characterInfo.list(params)
      if (result.code === 0 && result.data) {
        this.cacheStore.setCache(cacheKey, result, config.expireTime)
        console.log('后台缓存更新成功:', cacheKey)
      }
    } catch (error) {
      console.warn('后台缓存更新失败:', error)
    }
  }

  // 清除相关缓存
  clearRoleListCache(pattern?: string) {
    if (pattern) {
      // 清除匹配模式的缓存
      Object.keys(this.cacheStore.caches).forEach(key => {
        if (key.includes(pattern)) {
          this.cacheStore.clearCache(key)
        }
      })
    } else {
      // 清除所有角色列表缓存
      Object.keys(this.cacheStore.caches).forEach(key => {
        if (key.startsWith('roleList:')) {
          this.cacheStore.clearCache(key)
        }
      })
    }
  }

  // 预热缓存
  async warmupRoleListCache() {
    const commonParams = [
      { pageNum: 1, pageSize: 8 }, // 首页热门角色
      { pageNum: 1, pageSize: 20 }, // 探索页第一页
      { category: 'all', pageNum: 1, pageSize: 20 }, // 全部分类
    ]

    const promises = commonParams.map(params => 
      this.getRoleList(params, { expireTime: 10 * 60 * 1000 }) // 10分钟缓存
    )

    try {
      await Promise.allSettled(promises)
      console.log('缓存预热完成')
    } catch (error) {
      console.warn('缓存预热部分失败:', error)
    }
  }

  // 获取缓存统计
  getCacheStats() {
    const caches = this.cacheStore.caches
    const now = Date.now()
    
    let validCount = 0
    let expiredCount = 0
    let totalSize = 0

    Object.values(caches).forEach(cache => {
      totalSize += JSON.stringify(cache.data).length
      if ((now - cache.timestamp) < cache.expireTime) {
        validCount++
      } else {
        expiredCount++
      }
    })

    return {
      total: Object.keys(caches).length,
      valid: validCount,
      expired: expiredCount,
      size: totalSize
    }
  }
}

// 导出单例
export const cacheService = new CacheService()
